package com.katze.common.config;

import com.katze.common.http.HttpUtils;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Collections;
import java.util.HashSet;
import java.util.Objects;
import java.util.Set;

/**
 * 说  明：
 * 作  者：zf.zeng
 * 日  期：2022-12-20 (星期二)
 **/
@ConfigurationProperties(prefix = "app.mvc")
@ConditionalOnProperty(value = "app.mode", havingValue = "client")
public class WebMvcConfigurerAdapter implements WebMvcConfigurer {

    private final Set<String> allow = new HashSet<>();

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new URLInterceptor(this.allow)).addPathPatterns("/**");
    }

    public void setAllow(String allow) {
        Collections.addAll(this.allow, allow.split(","));
    }

    protected static class URLInterceptor implements HandlerInterceptor {
        private final Set<String> ip;

        public URLInterceptor(Set<String> ip) {
            this.ip = Objects.requireNonNull(ip);
        }

        //在请求处理之前进行调用（Controller方法调用之前）
        @Override
        public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
            if (this.ip.size() == 0 || this.ip.contains(HttpUtils.getRemoteAddress(request))) {
                return true;
            } else {
                response.setStatus(HttpStatus.NOT_ACCEPTABLE.value());
                return false;
            }
        }
    }
}
